package com.hexinfo.dmpro.monitor.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hexinfo.dmpro.monitor.model.base.MonitorRsp;
import com.hexinfo.dmpro.monitor.model.base.MonitorReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author peng
 * @date 2022/2/15 15:18
 */
@Slf4j
@Service
public class ClusteAllRolesService {

    private int SUCESS_CODE = 200;

    @Autowired
    private CmApiService cmApiService;

    private String apiUrl = "/clusters/{clusterName}/services";

    public JSONArray getAllRolesInfo(MonitorReq req, boolean flag) {

        JSONObject jsonObject = JSONObject.parseObject(req.getOtherParam());
        //配置cm Api的 url
        String url = jsonObject.get("cmApi").toString();
        req.setUrl(url);
        String user = jsonObject.get("user").toString();
        String password = jsonObject.get("password").toString();

        Map header = new HashMap<>();
        try {
            header.put("Authorization", "Basic " + Base64.getEncoder().encodeToString((user + ":" + password).getBytes("utf-8")));
            req.setHeader(header);
        } catch (UnsupportedEncodingException e) {
            log.error("设置Authorization异常", e);
        }
        JSONArray jsonArray = null;
        url += apiUrl;
        req.setUrl(url.replace("{clusterName}", req.getClusterFlag()));
        MonitorRsp rsp = cmApiService.execute(req);
        if (SUCESS_CODE == rsp.getCode()) {
            //删除某个集群数据 再新增集群数据
            String body = rsp.getBody();
            JSONObject obj = JSONObject.parseObject(body);
            jsonArray = obj.getJSONArray("items");
        }
        return jsonArray;
    }

    private String serviceApiUrl = "/clusters/{clusterName}/services/{service}?view=FULL_WITH_HEALTH_CHECK_EXPLANATION";
    public JSONObject getRequestCmApi(MonitorReq req, String service) {
        JSONObject jsonObject = JSONObject.parseObject(req.getOtherParam());
        //配置cm Api的 url
        String url = jsonObject.get("cmApi").toString();
        req.setUrl(url);
        String user = jsonObject.get("user").toString();
        String password = jsonObject.get("password").toString();

        Map header = new HashMap<>();
        try {
            header.put("Authorization", "Basic " + Base64.getEncoder().encodeToString((user + ":" + password).getBytes("utf-8")));
            req.setHeader(header);
        } catch (UnsupportedEncodingException e) {
            log.error("设置Authorization异常", e);
        }
        url += serviceApiUrl;
        req.setUrl(url.replace("{clusterName}",req.getClusterFlag()).replace("{service}",service));
        JSONObject rsp = cmApiService.getRequestCmApi(req);
        return rsp;
    }


}
